// 是否是list_cat页面

import { fetchApiData, fetchApiDataBatch, fetchCatList } from '@/utils/yapi'
import { sendMessage } from 'webext-bridge/window'

// /project/144/interface/api/cat_3272
export const isListCatPage = (href: string) => {
    return href.includes('interface/api/cat_')
}

// 获取cat_id
export const getCatId = (href: string) => {
    const catId = href.match(/cat_(\d+)/)?.[1]
    return catId
}

// 是否是api详情页，需要在list_cat判定之后再判定
export const isApiPage = (href: string) => {
    return href.includes('/interface/api/')
}

// 获取apiId
export const getApiId = (href: string) => {
    const apiId = href.match(/api\/(\d+)/)?.[1]
    return apiId
}

// 延迟
export const sleep = (ms: number) => {
    return new Promise((resolve) => setTimeout(resolve, ms))
}

// 获取按钮
export const createBtn = (text: string, onClick: () => void) => {
    const btn = document.createElement('button')
    btn.innerText = text
    btn.id = 'mock-response-import-btn'
    btn.className = 'ant-btn btn-filter ant-btn-primary'
    btn.style.marginLeft = '10px'
    btn.onclick = onClick
    return btn
}

// 检查，页面加载完成后或者url变化后运行
export const checkCurrentPage = async () => {
    const href = window.location.href
    if (!href) return

    // 往页面上插入按钮的容器
    let btnText = ''
    let onClickHandler = null
    let btnContainerSelector = ''

    // 如果是list_cat页面
    if (isListCatPage(href)) {
        const catId = getCatId(href)
        if (!catId) return
        btnContainerSelector = `.right-content .interface-title`
        btnText = 'Mock: 导入接口'
        onClickHandler = async () => {
            // 点击时才获取api列表
            const catList = await fetchCatList({
                baseUrl: window.location.origin,
                catId,
            })
            const apiIds = catList
                .map((item: any) => item?._id)
                ?.filter(Boolean)
            const apiList = (
                await fetchApiDataBatch({
                    baseUrl: window.location.origin,
                    apiIds,
                })
            )?.filter(Boolean)

            if (!apiList?.length) {
                alert('未获取到接口数据')
                return
            }

            const recommendGroupName = apiList[0]?.tag?.[0]
            sendMessage('importFromYapiPage', {
                recommendGroupName: recommendGroupName || '未命名',
                apiList,
            })
        }
    } else if (isApiPage(href)) {
        // 如果是api详情页面
        const apiId = getApiId(href)
        if (!apiId) return
        btnContainerSelector = `.caseContainer .interface-title`
        btnText = 'Mock: 导入接口'
        onClickHandler = async () => {
            // 点击时才获取api数据
            const apiList = [
                await fetchApiData({ baseUrl: window.location.origin, apiId }),
            ]?.filter(Boolean)

            if (!apiList?.length) {
                alert('未获取到接口数据')
                return
            }

            const recommendGroupName = apiList[0]?.tag?.[0]
            sendMessage('importFromYapiPage', {
                recommendGroupName: recommendGroupName || '未命名',
                apiList,
            })
        }
    }

    // 如果没有匹配到任何页面类型，直接返回
    if (!btnContainerSelector || !onClickHandler) return

    let btnContainer = null

    // 等待1秒，避免页面未加载完成
    await sleep(1000)

    // 尝试3次
    for (let i = 0; i < 3; i++) {
        btnContainer = document.querySelector(btnContainerSelector)
        if (btnContainer) break
        await sleep(1000)
    }

    if (!btnContainer || !onClickHandler) return

    const btn = createBtn(btnText, onClickHandler)
    // 删除已存在的按钮
    const oldBtn = btnContainer.querySelector('#mock-response-import-btn')
    if (oldBtn) {
        oldBtn?.remove()
    }
    btnContainer.appendChild(btn)
}

// 1. 重写 pushState 和 replaceState，手动派发事件
function patchHistoryAPI() {
    // 保存原生方法
    const originalPushState = history.pushState
    const originalReplaceState = history.replaceState

    // 重写 pushState
    history.pushState = function (...args) {
        const result = originalPushState.apply(this, args)
        // 派发自定义事件（命名为 custom-pushstate，避免和原生冲突）
        window.dispatchEvent(new Event('custom-pushstate'))
        return result
    }

    // 重写 replaceState
    history.replaceState = function (...args) {
        const result = originalReplaceState.apply(this, args)
        // 派发自定义事件
        window.dispatchEvent(new Event('custom-replacestate'))
        return result
    }
}

export const yapiImportCheck = async () => {
    // 2. 页面加载时执行重写
    window.addEventListener('DOMContentLoaded', () => {
        patchHistoryAPI() // 先重写 API
        checkCurrentPage() // 初始检查

        // 3. 监听所有路由相关事件（原生 + 自定义）
        window.addEventListener('popstate', checkCurrentPage) // 浏览器前进/后退
        window.addEventListener('custom-pushstate', checkCurrentPage) // pushState 触发
        window.addEventListener('custom-replacestate', checkCurrentPage) // replaceState 触发
        window.addEventListener('hashchange', checkCurrentPage) // hash 模式路由（如 #/home）
    })
}
